package com.jsn.android.audio2

import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.lifecycle.MutableLiveData
import com.jsn.baselibx.utils.Logs

class AudioPlayer {

    private val TAG = "AudioPlayer"
    private val DEFAULT_STREAM_TYPE = AudioManager.STREAM_MUSIC
    private val DEFAULT_SAMPLE_RATE = 44100
    private val DEFAULT_CHANNEL_CONFIG: Int = AudioFormat.CHANNEL_IN_STEREO
    private val DEFAULT_AUDIO_FORMAT: Int = AudioFormat.ENCODING_PCM_16BIT
    private val DEFAULT_PLAY_MODE = AudioTrack.MODE_STREAM

    var bufferSize=0

    //val session =111

    lateinit var audioTrack: AudioTrack

    val start=MutableLiveData<Boolean>().apply { value=false }

    fun startPlayer():Boolean{

        if(start.value!!) return true
        //size
        bufferSize=AudioTrack.getMinBufferSize(DEFAULT_SAMPLE_RATE,DEFAULT_CHANNEL_CONFIG,DEFAULT_AUDIO_FORMAT)
        if(bufferSize==AudioTrack.ERROR_BAD_VALUE)
            return false

        Log.d(TAG , "getMinBufferSize = "+bufferSize+" bytes !")

        audioTrack=AudioTrack(DEFAULT_STREAM_TYPE,DEFAULT_SAMPLE_RATE,DEFAULT_CHANNEL_CONFIG,DEFAULT_AUDIO_FORMAT,bufferSize,DEFAULT_PLAY_MODE)
        if(audioTrack.state==AudioTrack.STATE_UNINITIALIZED){
            Logs.e("audioTrack init fail ")
            return false
        }
        start.value=true
        return true
    }


    //just discard data in buffer and stop playing ,not release
    fun pause(){
        if(start.value==false) return
        if(audioTrack.playState==AudioTrack.PLAYSTATE_PLAYING){
            audioTrack.pause()
            audioTrack.flush()
        }
    }

    //stop and realease
    fun stop(){
        if(start.value==false) return
        if(audioTrack.playState==AudioTrack.PLAYSTATE_PLAYING){
            audioTrack.stop()
        }
        audioTrack.release()
        start.value=false
    }

    fun play(data:ByteArray,offsetInBytes:Int,sizeInBytes:Int):Boolean{
        if(!start.value!!) return false
        if(sizeInBytes<bufferSize) return false
        if(audioTrack.write(data,offsetInBytes,sizeInBytes)!=sizeInBytes){
            Log.e(TAG, "Could not write all the samples to the audio device !")
        }
        audioTrack.play()
        Logs.e("play ${sizeInBytes} bytes")
        return true
    }
}